package com.cositas.dulces.lp.promo2012;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Choice;
import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.cositas.dulces.lp.promo2012.utils.ActionsPoints;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class VotePrizeAction implements Action {
	
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws EntityNotFoundException, IOException, ServletException {
		String uid = req.getParameter("uid"); // el que invita
		String opt = req.getParameter("opt"); // lo que se vota
		String choice = req.getParameter("choice"); // la eleccion
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Key wallShareKey = KeyFactory.createKey(Choice.entity_name, uid + "-" + opt);
		try {
			datastore.get(wallShareKey);
		} catch (EntityNotFoundException e) {
			// circuito de puntaje
			Key participantKey = KeyFactory.createKey(Participant.entity_name, uid);
			Entity participant = datastore.get(participantKey);
			Integer account = Integer.valueOf((String)participant.getProperty(Participant.field_points));
			account = account + ActionsPoints.VOTE_PRIZE_POINTS;
			participant.setProperty(Participant.field_points, account.toString());
			datastore.put(participant);
			Entity wallShare = new Entity(wallShareKey);
			wallShare.setProperty(Choice.field_choice, choice);
			datastore.put(wallShare);
		}
		req.getRequestDispatcher("./votePrize.jsp").forward(req, resp);
	}
}
